<template>
  <div class="adoptions-container">
    <el-card class="adoptions-card">
      <template #header>
        <div class="card-header">
          <span>我的领养</span>
        </div>
      </template>

      <div class="adoption-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="已确认领养" name="pending"></el-tab-pane>
          <el-tab-pane label="已领养" name="adopted"></el-tab-pane>
        </el-tabs>
      </div>

      <div v-loading="loading" class="adoption-list">
        <div v-if="adoptionList.length === 0" class="empty-data">
          <el-empty description="暂无领养记录"></el-empty>
        </div>

        <el-row :gutter="20" v-else>
          <el-col
            v-for="(item, index) in adoptionList"
            :key="index"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card class="pet-card" shadow="hover">
              <div class="pet-image">
                <el-image
                  :src="item.petImage || ''"
                  fit="cover"
                  style="width: 100%; height: 180px"
                ></el-image>
                <div class="pet-status">
                  <el-tag :type="getStatusType(item.status)">
                    {{ getStatusText(item.status) }}
                  </el-tag>
                </div>
              </div>
              <div class="pet-info">
                <h3 class="pet-name">{{ item.petName }}</h3>
                <p class="pet-time">
                  申请时间：{{ formatDate(item.applyTime) }}
                </p>
                <div class="pet-actions">
                  <el-button
                    v-if="item.status === 'pending'"
                    type="danger"
                    size="small"
                    @click.stop="cancelAdoption(item.id)"
                  >
                    取消申请
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="viewPetDetail(item.petId)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="pagination-section" v-if="total > 0">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-size="queryParams.pageSize"
          :page-sizes="[8, 16, 24]"
          :current-page="queryParams.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { listRecipe, handleCancelAdoption } from "@/api/recipe";

const router = useRouter();
const loading = ref(false);
const activeTab = ref("all");
const total = ref(0);
const adoptionList = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
  status: "",
  userId: localStorage.getItem("userId") || "1", // 当前用户ID
});

// 获取我的领养列表
const getAdoptionList = () => {
  loading.value = true;

  // 从宠物列表API筛选当前用户的领养记录
  listRecipe({
    ...queryParams,
    orderByColumn: "create_time",
    isAsc: "desc",
  })
    .then((res) => {
      if (res.code === 200) {
        // 根据状态筛选宠物列表
        let filteredList = res.rows || [];

        // 只保留当前用户申请的宠物
        filteredList = filteredList.filter((pet) => {
          // 过滤条件：待领养或已领养状态且是当前用户申请的
          if (activeTab.value === "pending" && pet.status === "2") {
            return true; // 待领养(已确认领养)
          } else if (activeTab.value === "adopted" && pet.status === "3") {
            return true; // 已领养
          } else if (activeTab.value === "all") {
            return pet.status === "2" || pet.status === "3"; // 全部（待领养+已领养）
          }
          return false;
        });

        // 转换为领养记录格式
        adoptionList.value = filteredList.map((pet) => ({
          id: pet.recipeId,
          petId: pet.recipeId,
          petName: pet.recipeName,
          petImage: pet.coverImage,
          status: pet.status === "2" ? "pending" : "adopted",
          applyTime: pet.updateTime || pet.createTime,
        }));

        total.value = adoptionList.value.length;
      } else {
        ElMessage.error(res.msg || "获取领养列表失败");
      }
    })
    .catch((error) => {
      console.error("获取领养列表失败:", error);
      ElMessage.error("获取领养列表失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

// Tab切换处理
const handleTabChange = (tab) => {
  queryParams.status =
    tab.props.name === "all" ? "" : tab.props.name === "pending" ? "2" : "3";
  queryParams.pageNum = 1;
  getAdoptionList();
};

// 页码改变处理
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getAdoptionList();
};

// 每页条数改变处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getAdoptionList();
};

// 取消申请
const cancelAdoption = (id) => {
  ElMessageBox.confirm("确认取消该领养申请吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 调用API取消领养申请
      handleCancelAdoption(id)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("已取消领养申请");
            getAdoptionList(); // 刷新列表
          } else {
            ElMessage.error(res.msg || "操作失败");
          }
        })
        .catch((error) => {
          console.error("取消领养申请失败:", error);
          ElMessage.error("取消领养申请失败");
        });
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
    });
};

// 查看宠物详情
const viewPetDetail = (petId) => {
  router.push(`/pet/detail/${petId}`);
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "未知时间";
  if (typeof date === "string") {
    date = new Date(date);
  }
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 获取状态类型（用于标签颜色）
const getStatusType = (status) => {
  switch (status) {
    case "pending":
      return "warning";
    case "adopted":
      return "success";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case "pending":
      return "已确认领养";
    case "adopted":
      return "已领养";
    default:
      return "未知状态";
  }
};

onMounted(() => {
  getAdoptionList();
});
</script>

<style scoped>
.adoptions-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.adoptions-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.adoption-list {
  margin-top: 20px;
  min-height: 300px;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.pet-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
}

.pet-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.pet-image {
  position: relative;
  height: 180px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.pet-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.pet-info {
  padding: 15px 0;
}

.pet-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.pet-time {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #909399;
}

.pet-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.pet-actions .el-button {
  margin-left: 8px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 576px) {
  .pet-image {
    height: 160px;
  }
}
</style>
